﻿//Copyright (C) Riwut Libinuko, 2010 - Ideas For Free
//http://blog.libinuko.com

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using SharePointZip.Controller;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.IO;
using ICSharpCode.SharpZipLib.Core;

namespace SharePointZip.Tools
{
    /// <summary>
    /// Implementation <see cref="SharpZipLibCompressorBase&lt;TSource&gt;"/> to compress <see cref="Microsoft.SharePoint.SPFile"/>.
    /// </summary>
    public class SPFileCompressor : SharpZipLibCompressorBase<SPFile>
    {
        /// <summary>
        /// Create compressed <see cref="Microsoft.SharePoint.SPFile"/> using <see cref="ZipOutputStream"/>.
        /// </summary>
        /// <param name="zipEngine">Active compression engine</param>
        /// <param name="objSrc">SPFile to be compressed</param>
        public override void CreateCompressedStream(ZipOutputStream zipEngine, SPFile objSrc)
        {
            byte[] buffer = new byte[4096];


            ZipEntry entry = new ZipEntry(objSrc.Url);

            entry.DateTime = objSrc.TimeCreated;
            zipEngine.PutNextEntry(entry);

            using (Stream fs = objSrc.OpenBinaryStream())
            {

                int sourceBytes;
                do
                {
                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
                    zipEngine.Write(buffer, 0, sourceBytes);
                } while (sourceBytes > 0);
            }

            zipEngine.CloseEntry();
        }

    }
}
